package com.huwaiwai.zookeeper.demo02;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.I0Itec.zkclient.ZkClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by huweiwei on 2017/4/7.
 */
@AllArgsConstructor
@NoArgsConstructor
public class SimpleServer implements Runnable {

    public static void main(String [] args){
        int port1 = 18081;
        int port2 = 18082;
        SimpleServer server1 = new SimpleServer(port1);
        SimpleServer server2 = new SimpleServer(port2);
        new Thread(server1).start();
        new Thread(server2).start();
    }

    private int port;

    private void regServer() {
        ZkClient client = new ZkClient("127.0.0.1:2181", 60000, 1000);
        String path = "/test/server" + port;
        if (client.exists(path)) {
            client.delete(path);
        }
        client.createEphemeral(path, "127.0.0.1:" + port);
    }

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            regServer();
            System.out.println("server started at " + port);
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new SimpleServerHandler(socket)).start();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {}
            }
        }
    }
}

@AllArgsConstructor
@NoArgsConstructor
class SimpleServerHandler implements Runnable {
    private Socket socket;

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            while (true) {
                String body = in.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("Receive : " + body);
                out.println("Hello " + body);
            }
        } catch (Exception e) {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                this.socket = null;
            }
        }
    }
}
